# -*- coding:utf-8 -*-
from rest_framework import serializers
from apps.user.models import User
from rest_framework.validators import UniqueValidator
from utils.password_encode import get_md5
import datetime


class UserSerializer(serializers.ModelSerializer):
    # mobile 作为用户名进行登录，这里我们需要做一个唯一性的验证
    mobile = serializers.CharField(
        write_only=True,
        required=True,
        allow_blank=False,
        # 验证User表里所有数据的集合
        validators=[UniqueValidator(queryset=User.objects.all(), message="该号码已注册")]
    )
    birthday = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False)
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', required=False)
    # email = serializers.EmailField(required=False)
    password = serializers.CharField()

    # create 方法会被自动调用，这里可以做一些数据的验证或者是存储之前数据的加工
    def create(self, validated_data):
        # print("create 方法被调用了")
        # print(validated_data)
        validated_data["password"] = get_md5(validated_data["password"])
        validated_data["create_time"] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        result = User.objects.create(**validated_data)
        return result

    class Meta:
        model = User
        fields = "__all__"
